﻿//统一文件为utf-8编码编译
#pragma execution_character_set("utf-8")
///////////////////////////////////////////////////////////////////////////
// 文件名:     workthread.cpp
// 描述:
// 作者:      颜磊
// 创建工程：   SpaceClear
// 创建时间:   2024-07-24 15:34
///////////////////////////////////////////////////////////////////////////
#include "workthread.h"
#include "managercenter.h"
#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfoList>


WorkThread::WorkThread(QObject *parent) : QThread(parent)
{

}

WorkThread::~WorkThread()
{

}

quint64 WorkThread::dirFileSize(const QString &path)
{
    QDir dir(path);
    quint64 size = 0;
    //dir.entryInfoList(QDir::Files)返回文件信息
    foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files))
    {
        //计算文件大小
        size += fileInfo.size();
    }
    //dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)返回所有子目录，并进行过滤
    foreach(QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
    {
        //若存在子目录，则递归调用dirFileSize()函数
        size += dirFileSize(path + QDir::separator() + subDir);
    }
    return size;
}

/**
 * @brief GetFileInfoList 获取所有文件对象
 * @param path 文件加路径
 * @param recursion 是否递归遍历子文件夹
 * @return
 */
QFileInfoList GetFileInfoList(QString path,bool recursion)
{
    QDir dir(path);
    //列出dir(path)目录文件下所有文件和目录信息，存储到file_list容器
    QFileInfoList file_list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    if(recursion){
        //列出dir(path)目录下所有子文件夹
        QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
        //进行子文件夹folder_list递归遍历，将内容存入file_list容器
        for(int i= 0; i != folder_list.size(); i++)
        {
            QString name = folder_list.at(i).absoluteFilePath();
            QFileInfoList child_file_list = GetFileInfoList(name,recursion);
            file_list.append(child_file_list);
        }
    }
    return file_list;
}

QFileInfoList GetFileList(QFileInfoList file_info_list,QStringList suffixList){
    QFileInfoList fileInfoList;
    foreach(QFileInfo fileinfo, file_info_list)
    {
        if(suffixList.contains(fileinfo.suffix())){
            fileInfoList.append(fileinfo);
        }
    }
    return fileInfoList;
}


quint64 GetFileListSize(QFileInfoList fileInfoList){
    quint64 size = 0;
    foreach(QFileInfo fileInfo, fileInfoList)
    {
        //计算文件大小
        size += fileInfo.size();
    }
    return size;
}

void WorkThread::run()
{
    ManagerCenter* managerCenter = (ManagerCenter* )parent();
    while (managerCenter->getIsRun()){
        QList<ClearPath> clearPathList = managerCenter->getClearPathList();
        for(int i=0;i<clearPathList.size();i++){
            if(!clearPathList.at(i).enable) continue;
            //qDebug()<< QString("开始回收%1下的数据文件").arg(clearPathList.at(i).path) << clearPathList.at(i).data_number_enable <<  clearPathList.at(i).time_enable;
            //获取文件列表
            QFileInfoList  fileInfoList = GetFileInfoList(clearPathList.at(i).path,clearPathList.at(i).cascade); //获取列表，是否递归
            if(clearPathList.at(i).is_filter_suffix){
                QStringList suffixList = QString(clearPathList.at(i).filter_suffix).split("/");
                fileInfoList = GetFileList(fileInfoList,suffixList);
            }
            if(clearPathList.at(i).data_number_enable){
                quint64 size_of_file;
                size_of_file=GetFileListSize(fileInfoList);
                switch (clearPathList.at(i).unit_option) {
                case 0:size_of_file=size_of_file/1048576;break;
                case 1:size_of_file=size_of_file/1073741824;break;
                case 2:size_of_file=size_of_file/1099511627776;break;
                }
                while(size_of_file > clearPathList.at(i).data_number){
                    //暂时写删除最后一个文件/优化时记得改为删除时间最早的那一个
                    QFile::remove(fileInfoList.last().absoluteFilePath());
                    fileInfoList.removeLast();
                    size_of_file=GetFileListSize(fileInfoList);
                    switch (clearPathList.at(i).unit_option) {
                    case 0:size_of_file=size_of_file/1048576;break;
                    case 1:size_of_file=size_of_file/1073741824;break;
                    case 2:size_of_file=size_of_file/1099511627776;break;
                    }
                    QThread::msleep(10);
                };
            }
            if(clearPathList.at(i).time_enable){
                //时间判别删除
                QDateTime nowTime = QDateTime::currentDateTime();
                foreach(QFileInfo fileInfo, fileInfoList)
                {
                    QDateTime fileTime = clearPathList.at(i).time_option == 0 ? fileInfo.created() : fileInfo.lastModified();
                    int minutes = fileTime.secsTo(nowTime);
                    if(minutes >= clearPathList.at(i).elapsed){
                        qDebug() << "remove" << fileInfo.absoluteFilePath();
                        QFile::remove(fileInfo.absoluteFilePath());
                    }

                    QThread::msleep(10);
                }
            }
        }

        int times = 0;
        while(times<100 && managerCenter->getIsRun())
        {
            QThread::msleep(10);
            times++;
        }

    }
}

